import multer from 'multer';
import path from 'path';
import fs from 'fs';

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, file.fieldname + '-' + uniqueSuffix + ext);
  }
});

// 视频文件过滤器
const videoFileFilter = (req: any, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  // 允许的视频类型
  const allowedVideoTypes = /mp4|mov|avi|mkv|webm|flv|wmv/;
  const allowedImageTypes = /jpeg|jpg|png|gif|webp/;
  
  const extname = path.extname(file.originalname).toLowerCase();
  const isVideo = allowedVideoTypes.test(extname) || file.mimetype.startsWith('video/');
  const isImage = allowedImageTypes.test(extname) || file.mimetype.startsWith('image/');

  if (isVideo || isImage) {
    return cb(null, true);
  } else {
    cb(new Error('只允许上传图片或视频文件'));
  }
};

// 创建支持视频的multer实例
const uploadVideo = multer({
  storage: storage,
  limits: {
    fileSize: 100 * 1024 * 1024, // 100MB，支持大视频文件
  },
  fileFilter: videoFileFilter
});

export default uploadVideo;